package me.buick.util.snmp.core.dao.impl.snmp;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 
 * Version 1.0
 * 
 * @author buick
 *
 */
public final class SNMPDataPoller {

	private long interval = 0;
	private List<IPollable> pollerList = null;
	private PollerTask pollTask  = null;
	private Timer timer = null;
	private Object timerLock = new Object(); 
	
	SNMPDataPoller(long interval){
		if(interval <= 0)
			throw new IllegalArgumentException("Argument interval must be bigger than 0 :"+interval);
		
		this.interval = interval;
		this.pollerList = new java.util.LinkedList<IPollable>();
		pollTask = new PollerTask();
	}

	public void add(IPollable pollable)
	{
		if(pollable == null)
			return;
		synchronized(pollerList)
		{
			pollerList.add(pollable);
		}
		
	}
	
	public void remove(IPollable pollable)
	{
		if(pollable == null)
			return;
		synchronized(pollerList)
		{
			pollerList.remove(pollable);
		}
	}
	
	public void start()
	{
		synchronized(timerLock)
		{
			if(this.timer != null)
				return;
			this.timer = new Timer();
			timer.scheduleAtFixedRate(pollTask, 0, interval);
		}
	}
	
	public void stop(){
		
		synchronized(timerLock)
		{
			if(this.timer == null)
				return;
			
			this.timer.cancel();
			this.timer = null;
			
		}
	}

	protected class PollerTask extends TimerTask
	{
		
		long lastTime = -1;
		public void run() {
            if(pollerList.isEmpty())
            	return;
            
            long myinterval = SNMPDataPoller.this.interval;
            long nowTime    = System.currentTimeMillis();
            if(lastTime != -1)
            	myinterval  = nowTime - lastTime;
            lastTime = nowTime;
			synchronized(pollerList)
			{
				for(IPollable poller : SNMPDataPoller.this.pollerList){
					poller.poll(myinterval);	
				}
			}	
		}
	}

		

}
